#include "include/widgets/portfolio_widget.hpp"
#include <QHeaderView>

PortfolioWidget::PortfolioWidget(TradingSystem *tradingSystem, QWidget *parent)
    : QWidget(parent), m_tradingSystem(tradingSystem) {
  setupUI();
  setupConnections();
  refreshPortfolioTable();
}

void PortfolioWidget::setupUI() {
  // 创建主布局
  auto *mainLayout = new QVBoxLayout(this);

  // 资产信息
  auto *assetsLayout = new QHBoxLayout();
  m_balanceLabel = new QLabel("可用资金: ¥0.00", this);
  m_totalAssetsLabel = new QLabel("总资产: ¥0.00", this);
  assetsLayout->addWidget(m_balanceLabel);
  assetsLayout->addStretch();
  assetsLayout->addWidget(m_totalAssetsLabel);

  // 创建持仓表格
  m_portfolioTableView = new QTableView(this);
  m_portfolioModel = new QStandardItemModel(this);
  m_portfolioModel->setColumnCount(7);
  m_portfolioModel->setHorizontalHeaderLabels(
      {"代码", "名称", "持仓数量", "持仓均价", "现价", "盈亏(¥)", "盈亏(%)"});

  m_portfolioTableView->setModel(m_portfolioModel);
  m_portfolioTableView->horizontalHeader()->setSectionResizeMode(
      QHeaderView::Stretch);
  m_portfolioTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
  m_portfolioTableView->setSelectionMode(QAbstractItemView::SingleSelection);
  m_portfolioTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
  m_portfolioTableView->setSortingEnabled(true);

  // 设置委托来格式化显示
  m_portfolioDelegate = new StockTableDelegate(this);
  m_portfolioTableView->setItemDelegate(m_portfolioDelegate);

  // 刷新按钮
  auto *buttonLayout = new QHBoxLayout();
  m_refreshButton = new QPushButton("刷新", this);
  buttonLayout->addStretch();
  buttonLayout->addWidget(m_refreshButton);

  // 将控件添加到布局
  mainLayout->addLayout(assetsLayout);
  mainLayout->addWidget(m_portfolioTableView);
  mainLayout->addLayout(buttonLayout);
}

void PortfolioWidget::setupConnections() {
  connect(m_tradingSystem, &TradingSystem::accountUpdated, this,
          &PortfolioWidget::onAccountUpdated);
  connect(m_refreshButton, &QPushButton::clicked, this,
          &PortfolioWidget::refreshPortfolioTable);

  connect(
      m_portfolioTableView, &QTableView::clicked, this,
      [this](const QModelIndex &index) {
        int row = index.row();
        QString stockCode = m_portfolioModel->item(row, 0)->text();
        QString stockName = m_portfolioModel->item(row, 1)->text();
        double price =
            m_portfolioModel->item(row, 4)->data(Qt::DisplayRole).toDouble();

        emit stockSelected(stockCode, stockName, price);
      });
}

void PortfolioWidget::refreshPortfolioTable() {
  // 清空表格
  m_portfolioModel->removeRows(0, m_portfolioModel->rowCount());

  UserAccount *account = m_tradingSystem->getCurrentAccount();
  if (!account) {
    return;
  }

  // 更新余额和总资产显示
  double balance = account->getBalance();
  double totalAssets = account->getTotalAssets();

  m_balanceLabel->setText(QString("可用资金: ¥%1").arg(balance, 0, 'f', 2));
  m_totalAssetsLabel->setText(
      QString("总资产: ¥%1").arg(totalAssets, 0, 'f', 2));

  // 添加持仓数据
  const QVector<Position> &positions = account->getPositions();
  for (const auto &pos : positions) {
    QList<QStandardItem *> row;

    // 代码和名称
    row.append(new QStandardItem(pos.stockCode));
    row.append(new QStandardItem(pos.stockName));

    // 持仓数量
    auto *sharesItem = new QStandardItem();
    sharesItem->setData(pos.shares, Qt::DisplayRole);
    row.append(sharesItem);

    // 持仓均价
    auto *avgPriceItem = new QStandardItem();
    avgPriceItem->setData(pos.avgPrice, Qt::DisplayRole);
    row.append(avgPriceItem);

    // 现价
    auto *currentPriceItem = new QStandardItem();
    currentPriceItem->setData(pos.currentPrice, Qt::DisplayRole);
    row.append(currentPriceItem);

    // 盈亏金额
    auto *profitItem = new QStandardItem();
    double profit = pos.getProfit();
    profitItem->setData(profit, Qt::DisplayRole);
    if (profit > 0) {
      profitItem->setForeground(QBrush(Qt::red));
    } else if (profit < 0) {
      profitItem->setForeground(QBrush(Qt::green));
    }
    row.append(profitItem);

    // 盈亏百分比
    auto *profitPercentItem = new QStandardItem();
    double profitPercent = pos.getProfitPercent();
    profitPercentItem->setData(profitPercent, Qt::DisplayRole);
    if (profitPercent > 0) {
      profitPercentItem->setForeground(QBrush(Qt::red));
    } else if (profitPercent < 0) {
      profitPercentItem->setForeground(QBrush(Qt::green));
    }
    row.append(profitPercentItem);

    m_portfolioModel->appendRow(row);
  }
}

void PortfolioWidget::onAccountUpdated() { refreshPortfolioTable(); }
